<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: PagePathMan.php 425 2011-01-05 10:30:30Z steen.rabol $
 *
 */

prado::using('System.Xml.TXmlDocument');
Prado::using('Application.Common.Data.PortalPagePathRecord');
class PagePathMan extends PortalAdminPage
{
	public function onLoad($param)
	{
		parent::onLoad($param);
		$this->setAdminPageTitle('Pages');

		if(!$this->isPostBack)
		{
			$this->bindData();
		}
	}

	protected function bindData()
	{
		$offset	= $this->PagesGrid->CurrentPageIndex*$this->PagesGrid->PageSize;
		$limit	= $this->PagesGrid->PageSize;
		$ds		= $this->DataAccess->createCommand("select * from tblpagepath order by name LIMIT $offset,$limit")->query();
		$this->PagesGrid->DataSource = $ds;
		$this->PagesGrid->VirtualItemCount	=$ds->RowCount;
		$this->PagesGrid->dataBind();

		$this->dlRole->DataSource	= $this->DataAccess->createCommand("select id,name from tblroles")->query();
		$this->dlRole->dataBind();
	}

	public function onItemCommand($sender, $param)
	{
		switch($param->CommandName)
		{
		}
	}
	public function changePage($sender, $param)
	{
		$this->PagesGrid->CurrentPageIndex = $param->NewPageIndex;
		$this->bindData();
	}

	public function pagerCreated($sender, $param)
	{
		$param->Pager->Controls->insertAt(0, Prado::localize('Page').': ');
	}

	public function editItem($sender, $param)
	{
		$this->PagesGrid->EditItemIndex = $param->Item->ItemIndex;
		$this->bindData();
	}

	public function saveItem($sender, $param)
	{
		$item				= $param->Item;
		$ppRecord			= PortalPagePathRecord::finder()->findByid($this->PagesGrid->DataKeys[$item->ItemIndex]);
		$ppRecord->active	= TPropertyValue::ensureInteger($item->Cells[2]->PageStatus->SelectedValue);
		$ppRecord->role		= TPropertyValue::ensureInteger($item->Cells[3]->UserRole->SelectedValue);
		$ppRecord->save();

		$this->Application->BuildUrlMappingsForPath(true);
		$this->gotoPage('Admin.PagePathMan');
	}

	public function cancelItem($sender, $param)
	{
		$this->gotoPage('Admin.PagePathMan');
		$this->PagesGrid->EditItemIndex = -1;
		$this->PagesGrid->SelectedItemIndex = $param->Item->ItemIndex;
		$this->bindData();
	}

	public function deleteItem($sender, $param)
	{
		$item		= $param->Item;
		$Id			= $this->PagesGrid->DataKeys[$item->ItemIndex];
		$item		= $param->Item;
		$ppRecord	= PortalPagePathRecord::finder()->findByid($Id);

		// Check files in the path
		if($ppRecord->path == '' || $ppRecord->path === null) // Root
		{
			return;
		}

		// Files in path
		$newPath		= 'Application.Pages.' . $ppRecord->path;
		$fullNewPath	= Prado::getPathOfNamespace($newPath) . "/";
		$finp			= PortalUtil::getFilesInPath($fullNewPath);

		if($finp && count($finp) >0)
		{
			foreach($finp as $fp)
			{
				@unlink($fullNewPath . $fp);
			}
		}

		// Delete the path
		@rmdir($fullNewPath);
		PortalPagePathRecord::finder()->deleteByid($Id);
		$this->Application->BuildUrlMappingsForPath(true);
		$this->gotoPage('Admin.PagePathMan');
	}

	public function itemCreated(&$sender, $param)
	{
		$item = &$param->Item;

		if($item->ItemType === 'Item' || $item->ItemType === 'AlternatingItem' || $item->ItemType === 'EditItem')
		{
			// add an aleart dialog to delete buttons
			$item->DeleteColumn->Button->Attributes->onclick = 'if(!confirm(\'' . Prado::localize('This will also delete ALL pages in the path\nAre you sure?').'\')) return false;';
		}
	}

	public function ValidateUserRole($role)
	{
		$retval		= ' ';
		$first		= true;
		$validroles	= $this->getUserRoles();

		if($validroles)
		{
			foreach($validroles as $vvalue)
			{
				if($first)
				{
					$retval = $vvalue['id']; //In case we don't find our wanted we return a valid on :-)
					$first = false;
				}

				if($vvalue['id'] == $role)
				{
					return $role;
				}
			}
		}

		return $retval;
	}

	public function getYesNoData()
	{
		$pl = array();
		$pl[] = array("name" => Prado::localize("No"), "id" => 0);
		$pl[] = array("name" => Prado::localize("Yes"), "id" => 1);
		return $pl;
	}

	public function RoleName($p_role)
	{
		if($p_role == 0)
		{
			return Prado::localize("All");
		}

		return $this->DataAccess->createCommand("select name from tblroles where id = $p_role")->queryScalar();
	}

	public function AddPath($sender, $param)
	{
		if($this->IsValid)
		{
			$ppRec	= new PortalPagePathRecord();
			$ppRec->name	= $this->newName->Text;
			$ppRec->path	= $this->newPath->Text;
			$ppRec->active	= TPropertyValue::ensureInteger($this->newActive->Checked);
			$ppRec->role	= TPropertyValue::ensureInteger($this->dlRole->SelectedValue);
			$ppRec->save();

			// Create the path
			$newPath		= 'Application.Pages.' . $this->newPath->Text;
			$fullNewPath	= Prado::getPathOfNamespace($newPath);

			try
			{
				mkdir($fullNewPath,0777,true);

			}
			catch(Exception $e)
			{
				$this->reportError("Failed to create new directory: $fullNewPath<br>Error: " . $e->getMessage());
			}

			// Create the config.xml
			if(is_dir($fullNewPath))
			{
				$cfgfile			= $fullNewPath . '/' . 'config.xml';
				$doc				= new TXmlDocument('1.0','utf-8');
				$doc->TagName		= 'configuration';
				$proc				= new TXmlElement('authorization');
				$doc->Elements[]	= $proc;

				$allow			= new TXmlElement('allow');

				if($ppRec->role == 0)
				{
					$allow->setAttribute('roles',"*");
				}
				else
				{
					$allow->setAttribute('roles',$this->RoleName($ppRec->role));
				}

				$proc->Elements[] = $allow;
				$doc->saveToFile($cfgfile);
			}

			$this->Application->BuildUrlMappingsForPath(true);
			$this->gotoPage('Admin.PagePathMan');
		}
	}

	public function validatePathPath($sender,$param)
	{
		// Check path length
		$pArray	= explode("." , $this->newPath->Text);
		if(is_array($pArray))
		{
			foreach($pArray	as $p)
			{
				if(strlen($p) > 20)
				{
					$this->valPagePath->ErrorMessage = Prado::localize("Each path element can only be 20 characters long");
					$param->IsValid = false;
					return;
				}
			}
		}

		// Check if we already have a path like this
		$param->IsValid = PortalPagePathRecord::finder()->findBypath($this->newPath->Text) == null ? true : false;
	}

	public function validatePathName($sender,$param)
	{
		$param->IsValid = PortalPagePathRecord::finder()->findByname($this->newName->Text) == null ? true : false;
	}
}
?>